package com.fanqwz.kotlinmvvm.common.util.log

import android.util.Log
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.LoggerContext
import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * Created by fanqwz on 2017/10/27.
 */
class AndroidRollingFileAppender<T>: RollingFileAppender<T>() {

    companion object {
        fun addToRootLogger(appid:String, dir: String) {
            Log.d(AndroidRollingFileAppender::class.java.simpleName, "add rolling file appender to dir $dir")
            val context = LoggerFactory.getILoggerFactory() as LoggerContext
//            context.reset()   //don't clear the logccat appender decleared in logback.xml


            val rollingFileAppender = AndroidRollingFileAppender<ILoggingEvent>()
            rollingFileAppender.isAppend = true
            rollingFileAppender.setContext(context)

            // OPTIONAL: Set an active log file (separate from the rollover files).
            // If rollingPolicy.fileNamePattern already set, you don't need this.
            //rollingFileAppender.setFile(LOG_DIR + "/log.txt");

            val rollingPolicy = TimeBasedRollingPolicy<ILoggingEvent>()
            rollingPolicy.fileNamePattern = dir + "/log/${appid}_%d{yyyyMMdd}.txt"
            rollingPolicy.maxHistory = 7
            rollingPolicy.setParent(rollingFileAppender)  // parent and context required!
            rollingPolicy.context = context
            rollingPolicy.start()

            rollingFileAppender.rollingPolicy = rollingPolicy

            val encoder = PatternLayoutEncoder()
            encoder.pattern = "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n"
            encoder.context = context
            encoder.start()

            rollingFileAppender.encoder = encoder
            rollingFileAppender.start()

//            val logcatAppender = LogcatAppender()
//            logcatAppender.context = context
//            logcatAppender.encoder = encoder
//            logcatAppender.name = "logcat1"
//            logcatAppender.start()

            // add the newly created appenders to the root logger;
            // qualify Logger to disambiguate from org.slf4j.Logger
            val root = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME) as ch.qos.logback.classic.Logger
            root.level = Level.TRACE
            root.addAppender(rollingFileAppender)
//            root.addAppender(logcatAppender)

            // print any status messages (warnings, etc) encountered in logback config
            //StatusPrinter.print(context);


        }
      }
}